//
//  JoLoginViewController.m
//  RunningMan
//
//  Created by 姜勇利 on 16/5/18.
//  Copyright © 2016年 JohnnyB. All rights reserved.
//

#import "JoLoginViewController.h"
#import "Masonry.h"
#import "JoPrivatismViewController.h"
#import "JoUserNavigationViewController.h"
#import "JoSignViewController.h"
#import "EMSDk.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>


#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define WIDTH [UIScreen mainScreen].bounds.size.width

@interface JoLoginViewController ()<UITextFieldDelegate>

// 毛玻璃
@property (nonatomic, strong) UIBlurEffect *blurEffect;
@property (nonatomic, strong) UIVisualEffectView *visualEffectView;
@property (nonatomic, strong) UIImageView *imageCircle1;
@property (nonatomic, strong) UIImageView *imageCircle2;
// 动画载体
@property (nonatomic, strong) CALayer *layer;
// 背景图片
@property (nonatomic, strong) UIImageView *backImage;
// 头像图片
@property (nonatomic, strong) UIImageView *userImage;
// 白线
@property (nonatomic, strong) UIView *whiteLine;
// 登录按钮
@property (nonatomic, strong) UIButton *loginButton;
// 注册按钮
@property (nonatomic, strong) UIButton *signButton;
// 用户名
@property (nonatomic, strong) UITextField *nameTextField;
// 密码
@property (nonatomic, strong) UITextField *passwordTextFiled;
// 用户名
@property (nonatomic, strong) UILabel *nameLabel;
// 三方登录按钮
@property (nonatomic, strong) UIButton *weixinButton;
@property (nonatomic, strong) UIButton *weoboButton;
@property (nonatomic, strong) UIButton *QQButton;

@end

@implementation JoLoginViewController

#pragma mark -
- (void)loadView
{
    [super loadView];
    BOOL isAutoLogin = [EMClient sharedClient].options.isAutoLogin;
    if (isAutoLogin) {
        // 进入个人中心界面
        JoPrivatismViewController *privatism = [[JoPrivatismViewController alloc]init];
        JoUserNavigationViewController *userNavigationController = [[JoUserNavigationViewController alloc]initWithRootViewController:privatism];
        [self presentViewController:userNavigationController animated:YES completion:^{
            
        }];
    }
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self creatSubViews];
}

#pragma mark - 
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - 
- (void)creatSubViews
{
    self.backImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"3.jpg"]];
    [self.view addSubview:self.backImage];
    [self.backImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.right.equalTo(self.view).insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.backImage.userInteractionEnabled = YES;
    
    self.userImage = [[UIImageView alloc]init];
    [self.backImage addSubview:self.userImage];
    self.userImage.clipsToBounds = YES;
    self.userImage.backgroundColor = [UIColor yellowColor];
    [self.userImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backImage.mas_centerX);
        make.top.equalTo(self.backImage.mas_top).with.offset(HEIGHT / 7.f);
        make.width.height.mas_equalTo(HEIGHT / 10.f);
    }];
    self.userImage.layer.cornerRadius = HEIGHT / 20.f;
    self.userImage.image = [UIImage imageNamed:@"1401835_shi04.jpg"];
    
    self.nameLabel = [[UILabel alloc]init];
    [self.backImage addSubview:self.nameLabel];
    self.nameLabel.textColor = [UIColor whiteColor];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.equalTo(self.userImage.mas_bottom).with.offset(10);
        make.width.mas_equalTo(WIDTH / 3.f);
        make.height.mas_equalTo(HEIGHT / 30.f);
    }];
    self.nameLabel.text = @"请先登录";
    self.nameLabel.textAlignment = YES;
    self.nameLabel.font = [UIFont systemFontOfSize:15];
    
    UILabel *userNameLabel = [[UILabel alloc]init];
    [self.backImage addSubview:userNameLabel];
    userNameLabel.text = @"用户名:";
//    userNameLabel.textAlignment = YES;
    userNameLabel.font = [UIFont systemFontOfSize:16];
    userNameLabel.textColor = [UIColor whiteColor];
    [userNameLabel sizeToFit];
    [userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nameLabel.mas_bottom).with.offset(40);
        make.left.equalTo(self.view).with.offset(WIDTH / 6.f);
        make.width.mas_equalTo(WIDTH / 6.f);
//        make.right.equalTo(self.view.mas_right).with.offset(-WIDTH / 5.f);
        make.height.mas_equalTo(HEIGHT / 30.f);
    }];
    
    self.nameTextField = [[UITextField alloc]init];
    self.nameTextField.delegate = self;
    self.nameTextField.tag = 100;
    [self.backImage addSubview:self.nameTextField];
    [self.nameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(userNameLabel.mas_right).with.offset(0);
        make.width.mas_equalTo(WIDTH / 2.f + 10);
        make.height.mas_equalTo(HEIGHT / 30.f);
        make.centerY.mas_equalTo(userNameLabel.mas_centerY);
    }];
    self.nameTextField.returnKeyType = UIReturnKeyDone;
    self.nameTextField.placeholder = @"请输入邮箱/手机号/用户名";
//    self.nameTextField.textAlignment = YES;
    self.nameTextField.font = [UIFont systemFontOfSize:16];
    self.nameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *whiteView = [[UIView alloc]init];
    [self.backImage addSubview:whiteView];
    whiteView.backgroundColor = [UIColor whiteColor];
    [whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1.5);
        make.width.mas_equalTo(WIDTH * 2.8 / 4);
        make.centerX.mas_equalTo(self.backImage.mas_centerX);
        make.top.equalTo(userNameLabel.mas_bottom).with.offset(2);
    }];
    
    UILabel *passwordLabel = [[UILabel alloc]init];
    [self.backImage addSubview:passwordLabel];
    [passwordLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(whiteView.mas_bottom).with.offset(20);
        make.left.equalTo(self.view).with.offset(WIDTH / 6.f);
        make.width.mas_equalTo(WIDTH / 6.f);
        make.height.mas_equalTo(HEIGHT / 30.f);
    }];
    passwordLabel.font = [UIFont systemFontOfSize:16];
    passwordLabel.textColor = [UIColor whiteColor];
    passwordLabel.text = @"密    码:";
    [passwordLabel sizeToFit];
    passwordLabel.adjustsFontSizeToFitWidth = YES;
    
    self.passwordTextFiled = [[UITextField alloc]init];
    [self.backImage addSubview:self.passwordTextFiled];
    [self.passwordTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(passwordLabel.mas_right).with.offset(0);
        make.width.mas_equalTo(WIDTH / 2.f);
        make.height.mas_equalTo(HEIGHT / 30.f);
        make.centerY.mas_equalTo(passwordLabel.mas_centerY);
    }];
    self.passwordTextFiled.placeholder = @"请输入密码";
    self.passwordTextFiled.font = [UIFont systemFontOfSize:16];
    self.passwordTextFiled.secureTextEntry = YES;
    self.passwordTextFiled.delegate = self;
    self.passwordTextFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordTextFiled.returnKeyType = UIReturnKeyJoin;
    
    UIView *secWhiteView = [[UIView alloc]init];
    [self.backImage addSubview:secWhiteView];
    [secWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1.5);
        make.width.mas_equalTo(WIDTH * 2.8 / 4);
        make.centerX.mas_equalTo(self.backImage.mas_centerX);
        make.top.equalTo(passwordLabel.mas_bottom).with.offset(2);
    }];
    secWhiteView.backgroundColor = [UIColor whiteColor];
    
    self.loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backImage addSubview:self.loginButton];
    [self.loginButton setTintColor:[UIColor whiteColor]];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(secWhiteView.mas_bottom).with.offset(45);
        make.width.mas_equalTo(WIDTH / 1.5f);
        make.height.mas_equalTo(HEIGHT / 18.f);
        make.centerX.mas_equalTo(self.backImage.mas_centerX);
//        make.left.equalTo(self.backImage).with.offset(WIDTH / 6.f);
    }];
//    self.loginButton.backgroundColor = [UIColor cyanColor];
    self.loginButton.layer.borderColor = [[UIColor whiteColor]CGColor];
    self.loginButton.layer.borderWidth = 1.5;
    self.loginButton.clipsToBounds = YES;
    self.loginButton.layer.cornerRadius = 5;
    [self.loginButton addTarget:self action:@selector(handleLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    self.signButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backImage addSubview:self.signButton];
    [self.signButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.signButton setTintColor:[UIColor whiteColor]];
    self.signButton.clipsToBounds = YES;
    self.signButton.layer.borderWidth = 1.5;
    self.signButton.layer.borderColor = [[UIColor whiteColor]CGColor];
    [self.signButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loginButton.mas_bottom).with.offset(30);
        make.width.mas_equalTo(WIDTH / 1.5f);
        make.height.mas_equalTo(HEIGHT / 18.f);
        make.centerX.mas_equalTo(self.backImage.mas_centerX);
//        make.left.equalTo(self.backImage).with.offset(WIDTH / 6.f);
    }];
    self.signButton.layer.cornerRadius = 5;
    [self.signButton addTarget:self action:@selector(handleSign:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *weixinButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backImage addSubview:weixinButton];
    [weixinButton setImage:[UIImage imageNamed:@"5"] forState:UIControlStateNormal];
    [weixinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(WIDTH / 5.f);
        make.height.width.mas_equalTo(45);
        make.top.equalTo(self.signButton.mas_bottom).with.offset(35);
    }];
// 微信登录
    weixinButton.tag = 100;
    [weixinButton addTarget:self action:@selector(handleThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *weiboButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backImage addSubview:weiboButton];
    [weiboButton setImage:[UIImage imageNamed:@"6"] forState:UIControlStateNormal];
    [weiboButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.signButton.mas_bottom).with.offset(35);
        make.height.width.mas_equalTo(45);
        make.centerX.mas_equalTo(self.backImage.mas_centerX);
    }];
// 微博登录
    weiboButton.tag = 200;
    [weiboButton addTarget:self action:@selector(handleThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *QQButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backImage addSubview:QQButton];
    [QQButton setImage:[UIImage imageNamed:@"7"] forState:UIControlStateNormal];
    [QQButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).with.offset(-WIDTH / 5.f);
        make.height.width.mas_equalTo(45);
        make.top.equalTo(self.signButton.mas_bottom).with.offset(35);
    }];
// QQ登录
    QQButton.tag = 300;
    [QQButton addTarget:self action:@selector(handleThirdLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *forgetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backImage addSubview:forgetButton];
    [forgetButton setTintColor:[UIColor whiteColor]];
    [forgetButton setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(-20);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.width.mas_equalTo(WIDTH / 6.f);
        make.height.mas_equalTo(25);
    }];
    forgetButton.titleLabel.font = [UIFont systemFontOfSize:12];
    
    [self returnKeyborad];
}

#pragma mark - 回收键盘
- (void)returnKeyborad
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(CancelKey:)];
    [self.backImage addGestureRecognizer:tap];
}

- (void)CancelKey:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
}

#pragma mark - button点击事件
// 登录按钮
- (void)handleLogin:(UIButton *)button
{
    [self.view endEditing:YES];
    //毛玻璃
    self.blurEffect=[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    self.visualEffectView=[[UIVisualEffectView alloc]initWithEffect:self.blurEffect];
    [self.visualEffectView setFrame:self.view.bounds];
    [self.view addSubview:self.visualEffectView];
    
    UIImageView *userImage = [[UIImageView alloc]init];
    [self.visualEffectView addSubview:userImage];
    userImage.frame = CGRectMake(self.view.center.x - HEIGHT / 20.f, HEIGHT / 7.f, HEIGHT / 10.f, HEIGHT / 10.f);
    userImage.clipsToBounds = YES;
    userImage.layer.cornerRadius = HEIGHT / 20.f;
    UIImage *image = [UIImage imageNamed:@"1401835_shi04.jpg"];
    UIGraphicsBeginImageContextWithOptions(userImage.bounds.size, NO, 1.0);
    [[UIBezierPath bezierPathWithRoundedRect:userImage.bounds cornerRadius:75]addClip];
    [image drawInRect:userImage.bounds];
    userImage.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    [UIView animateWithDuration:0.5 animations:^{
        userImage.center = CGPointMake(WIDTH / 2.f, HEIGHT / 3.f);
        userImage.transform = CGAffineTransformScale(userImage.transform, 1500 / HEIGHT, 1500 / HEIGHT);
    }];
    
    self.imageCircle1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"clock_circle1"]];
    self.imageCircle1.frame = CGRectMake(0, 0, 150, 150);
    self.imageCircle1.center = CGPointMake(WIDTH / 2.f, HEIGHT / 3.f);
    [self.view addSubview:self.imageCircle1];
    
    self.imageCircle2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"clock_circle2"]];
    self.imageCircle2.frame = CGRectMake(0, 0, 170, 170);
    self.imageCircle2.center = CGPointMake(WIDTH / 2.f, HEIGHT / 3.f);
    [self.view addSubview:self.imageCircle2];
    //动画载体
    self.layer = [CALayer layer];
    self.layer.frame = CGRectMake(0, 0, 207, 207);
    self.layer.position = CGPointMake(WIDTH / 2.f + 1, HEIGHT / 3.f + 1);
    [self.view.layer addSublayer:self.layer];
    //设置动画代理
    self.layer.delegate = self;
    //设置动画
    [self.layer setNeedsDisplay];
    //动画  作用在layer某个属性上，动画效果不会影响layer原有的属性值
    CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    //动画时长
    animation.duration = 1.0;
    //动画的初始值
    animation.fromValue = [NSNumber numberWithFloat:0];
    //动画的结束时的值
    animation.toValue = [NSNumber numberWithFloat:((360*M_PI)/180)];
    //动画结束时的状态
    /*
     kCAFillModeForwards   保持结束时的状态
     kCAFillModeBackwards    回到开始时的状态
     kCAFillModeBoth         兼顾以上的两种效果
     kCAFillModeRemoved      结束时删除效果
     */
    animation.fillMode = kCAFillModeForwards;
    //动画的重复次数
    animation.repeatCount = HUGE_VALF;
    //开始动画
    [self.layer addAnimation:animation forKey:@"rotation"];
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.visualEffectView addSubview:cancelButton];
    [cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [cancelButton setTintColor:[UIColor whiteColor]];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.visualEffectView.mas_centerX);
        make.width.mas_equalTo(WIDTH / 4.f);
        make.height.mas_equalTo(HEIGHT / 25.f);
        make.top.equalTo(self.visualEffectView).with.offset(HEIGHT / 1.8f);
    }];
    cancelButton.layer.borderColor = [[UIColor whiteColor]CGColor];
    cancelButton.layer.borderWidth = 1.5;
    cancelButton.clipsToBounds = YES;
    cancelButton.layer.cornerRadius = 5;
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelButton addTarget:self action:@selector(handleRemove:) forControlEvents:UIControlEventTouchUpInside];
//  登录
    EMError *error = [[EMClient sharedClient] loginWithUsername:self.nameTextField.text password:self.passwordTextFiled.text];
    if (!error) {
        // 设置为自动登录
        [[EMClient sharedClient].options setIsAutoLogin:YES];
        NSLog(@"登录成功");
        // 进入个人中心界面
        JoPrivatismViewController *privatism = [[JoPrivatismViewController alloc]init];
        JoUserNavigationViewController *userNavigationController = [[JoUserNavigationViewController alloc]initWithRootViewController:privatism];
        [self presentViewController:userNavigationController animated:YES completion:^{
            
        }];
    }
}

- (void)handleRemove:(UIButton *)button
{
    EMError *error = [[EMClient sharedClient] logout:YES];
    if (!error) {
        NSLog(@"退出成功");
    }
    [self.imageCircle1 removeFromSuperview];
    [self.imageCircle2 removeFromSuperview];
    [self.layer removeFromSuperlayer];
    [self.visualEffectView removeFromSuperview];
}

// 实现代理方法
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    CGContextSaveGState(ctx);
    UIImage * image = [UIImage imageNamed:@"clock_circle3"];
    CGContextDrawImage(ctx, CGRectMake(0, 0, 207, 207), image.CGImage);
    CGContextRestoreGState(ctx);
}

// 进入注册界面
- (void)handleSign:(UIButton *)button
{
    JoSignViewController *signViewController = [[JoSignViewController alloc]init];
    [self presentViewController:signViewController animated:YES completion:^{
        
    }];
}

  // QQ登录
- (void)handleThirdLogin:(UIButton *)button
{
    if (button.tag == 300) {
        //例如QQ的登录
        [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeQQ
                                       onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                           
                                           //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
                                           //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
                                           associateHandler (user.uid, user, user);
                                           NSLog(@"dd%@",user.rawData);
                                           NSLog(@"dd%@",user.credential);
                                           
                                       }
                                    onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                        
                                        if (state == SSDKResponseStateSuccess)
                                        {
                                            
                                        }
                                        
                                    }];
    }
    
    if (button.tag == 200) {
        [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeSinaWeibo
                                       onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                           
                                           //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
                                           //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
                                           associateHandler (user.uid, user, user);
                                           NSLog(@"dd%@",user.rawData);
                                           NSLog(@"dd%@",user.credential);
                                           
                                       }
                                    onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                        
                                        if (state == SSDKResponseStateSuccess)
                                        {
                                            
                                        }
            }];
         }
    
    if (button.tag == 100) {
        [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeWechat onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
            associateHandler (user.uid, user, user);
        } onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
            if (state == SSDKResponseStateSuccess)
            {
                
            }

        }];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
